package com.qys.livesMall.app.user.controller.sys;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.app.user.model.dto.sys.EditSysAppUserDTO;
import com.qys.livesMall.app.user.model.dto.sys.QueryUserChannelDTO;
import com.qys.livesMall.app.user.model.dto.sys.SysAppUserQueryDTO;
import com.qys.livesMall.app.user.model.dto.sys.SysAppUserSaveDTO;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.model.vo.TelephoneAreaCodeVO;
import com.qys.livesMall.app.user.model.vo.sys.NewSysAppUserVo;
import com.qys.livesMall.app.user.model.vo.sys.SysAppUserActivePageVo;
import com.qys.livesMall.app.user.model.vo.sys.SysAppUserPageVo;
import com.qys.livesMall.app.user.model.vo.sys.UserChannelVO;
import com.qys.livesMall.app.user.service.AppUserRelationService;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.ip.IpUtil;
import com.qys.livesMall.framework.view.BaseQuery;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author dp
 * @since 2023-04-20
 */
@RestController
@RequestMapping("/sys/app/user")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Tag(name = "sys-app用户信息")
public class SysH2AppUserController {

    private final IH2AppUserService appUserService;

    private final AppUserRelationService appUserRelationService;
    @PostMapping("/page")
    @Operation(summary = "分页查询用户信息")
    public R<Page<SysAppUserPageVo>> page(@RequestBody SysAppUserQueryDTO userQueryDTO) {
        return R.ok(appUserService.pageSys(userQueryDTO));
    }

    @PostMapping("/foundationpage")
    @Operation(summary = "分页查询用户信息")
    public R<Page<SysAppUserPageVo>> foundationpage(@RequestBody SysAppUserQueryDTO userQueryDTO) {
        return R.ok(appUserService.foundationpage(userQueryDTO));
    }

    @PostMapping("/add")
    @Operation(summary = "新增用户信息")
    public R<Void> save(@RequestBody @Validated SysAppUserSaveDTO sysAppUserSaveDTO, HttpServletRequest request) {
        String ip = IpUtil.getIpAddr(request);
        appUserService.save(sysAppUserSaveDTO,ip);
        return R.ok();
    }

    @PostMapping("/addChannel")
    @Operation(summary = "新增渠道信息")
    public R<Void> addChannel(@RequestBody @Validated SysAppUserSaveDTO sysAppUserSaveDTO) {
        appUserService.addChannel(sysAppUserSaveDTO);
        return R.ok();
    }

    @PostMapping("/edit")
    @Operation(summary = "修改用户信息")
    public R<Void> edit(@RequestBody NewSysAppUserVo dto) {
        appUserService.update(dto);
        return R.ok();
    }

    @PostMapping("/editUser")
    @Operation(summary = "修改用户信息")
    public R<Void> editUser(@RequestBody EditSysAppUserDTO dto) {
        appUserService.editUser(dto);
        return R.ok();
    }

    /**
     * 冻结/解冻用户
     *
     * @param id 用户id
     * @return 修改结果
     */
    @GetMapping("/changeState/{id}")
    @Operation(summary = "冻结/解冻用户")
    public R<?> changeState(@PathVariable String id) {
        H2AppUser appUser = appUserService.getById(id);
        if(null==appUser){
            return R.fail();
        }
        H2AppUser h2AppUser = new H2AppUser();
        h2AppUser.setId(id);
        h2AppUser.setStatus(1 == appUser.getStatus() ? 0 : 1);
        appUserService.updateById(h2AppUser);
        return R.ok();
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据id查询用户信息")
    public R<NewSysAppUserVo> queryById(@PathVariable String id) {
        return R.ok(appUserService.queryById(id));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "根据id删除用户信息")
    public R<Void> removeById(@PathVariable String id) {
        appUserService.removeById(id);
        return R.ok();
    }

    @PutMapping("/top/{userId}/{top}")
    @Operation(
            summary = "置顶用户信息",
            parameters = {
                    @Parameter(name = "userId", description = "用户id"),
                    @Parameter(name = "top", description = "是否置顶")
            }
    )
    public R<Void> top(@PathVariable String userId, @PathVariable boolean top) {
        appUserService.top(userId, top);
        return R.ok();
    }

    @PutMapping("/water/army/{userId}")
    @Operation(summary = "设置/取消水军")
    public R<Void> waterArmy(@PathVariable String userId) {
        appUserService.waterArmy(userId);
        return R.ok();
    }

    @PostMapping("/userChannel")
    @Operation(summary = "查询用户下级渠道")
    public R<IPage<UserChannelVO>> queryUserChannel(@RequestBody QueryUserChannelDTO dto){
        LambdaQueryWrapper<H2AppUser> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(dto.getUserId())){
            queryWrapper.eq(H2AppUser::getSuperior,dto.getUserId());
        } else {
            queryWrapper.isNull(H2AppUser::getSuperior);
        }
        queryWrapper.orderByDesc(H2AppUser::getCreateTime);
        IPage<UserChannelVO> page = appUserService.page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper).convert(e -> {
            UserChannelVO vo = new UserChannelVO();
            vo.setId(Long.parseLong(e.getId()));
            vo.setUserName(e.getUserName());
            vo.setNickName(e.getNickName());
            vo.setUserSysType(e.getUserSysType());
            vo.setInvitationCode(e.getInvitationCode());
            vo.setPromotionAddress("http://www.xxx.com?inviteCode=" + e.getInvitationCode());
            vo.setJuniorNum(querySubordinateQuantity(e.getId()));
            return vo;
        });
        return R.ok(page);
    }

    private int querySubordinateQuantity(String parentId){
        int total = 0;
        List<H2AppUser> list = appUserService.list(Wrappers.<H2AppUser>lambdaQuery().select(H2AppUser::getId).eq(H2AppUser::getSuperior, parentId));
        if(CollectionUtils.isNotEmpty(list)){
            total += list.size();
            for (H2AppUser h2AppUser : list) {
                total += querySubordinateQuantity(h2AppUser.getId());
            }
        }
        return total;
    }


    @PostMapping("/activeUserPage")
    @Operation(summary = "分页查询活跃用户信息")
    public R<Page<SysAppUserActivePageVo>> activeUserPage(@RequestBody BaseQuery baseQuery) {
        return R.ok(appUserService.activeUserPage(baseQuery));
    }

    @GetMapping("/getInternationalTelephoneAreaCode")
    @Operation(summary = "获取国际电话区号")
    public R<List<TelephoneAreaCodeVO>> getInternationalTelephoneAreaCode() {
        return R.ok(appUserService.getInternationalTelephoneAreaCode());
    }


    @GetMapping("/getUserSubordinate/{userId}")
    @Operation(summary = "获取用户下级")
    public R<List<H2AppUser>> getUserSubordinate(@PathVariable Long userId) {
        return R.ok(appUserRelationService.getLowerLevels(userId));
    }
}
